<?php
/*
 * @Description    : 喵付通异步通知
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2022-03-16 14:50:04
 * @LastEditors    : QianLong
 * @LastEditTime   : 2023-10-28 17:19:27
 * @HomeUrl        : http://ecmpay.cn
 */

namespace app\api\controller;

use app\BaseController;
use app\common\model\Manager;
use app\lib\Result;
use think\facade\Validate;

class Notify extends BaseController
{
  // 使用带参数二维码扫码登录接口
  public function wechat_bind()
  {
    $ip = get_client_ip();
    if (request()->isPost()) {
      $rule = [
        'event_key'  => 'require',
        'open_id'  => 'require',
      ];
      $data = [
        'event_key'  => input('param.event_key', '', 'trim'),
        'open_id'  => input('param.open_id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Success(['content' => $validate->getError()], 'fail');
      }
      $event_key = $data['event_key'];
      $open_id = $data['open_id'];
      $event_key = str_replace('ldp_bind::', '', $event_key);
      if (empty($open_id)) {
        return Result::Success(['content' => '必要参数为空'], 'fail');
      }
      $hasUser = Manager::field('id,username')->where('wechat_open_id', $open_id)->find();
      if (!empty($hasUser) && $hasUser['id'] != $event_key) {
        return Result::Success(['content' => '当前微信号已绑定其他账号，请更换微信号重新绑定'], 'fail');
      }
      $hasUser2 = Manager::field('id,username')->where('id', $event_key)->find();
      if (empty($hasUser2)) {
        return Result::Success(['content' => '用户不存在，请刷新页面后尝试重新绑定'], 'fail');
      }
      Manager::where('id', $event_key)->update(['wechat_open_id'=> $open_id]);
      return Result::Success(['content' => $hasUser2['username'] . ' 通过扫码绑定柠聚开发者账号成功'], 'success');
    }
    return Result::Success(['content' => '请求不正常'], 'fail');
  }
}
